
//选择设备列表

var myChart;
var $box = document.getElementById('chartbox');

var chartData = {
    markline: 1,
    gap: 1000,//时间轴1秒间隔，转换为小时修改此设置即可，单位为毫秒
    timeFormat: 's',//x轴时间显示格式，分为 s,m,h三种  s->hh:mm:ss  m->hh:mm  h->h时
    curTime: '',//当前时间
    timer: {},//动态数据定时器
    deviceList: [2],//显示的设备id列表
    dataSet: {},//曲线数据
    timeLine: [],//时间轴
    init: function () {
        var that = this;
        this.time = new Date(new Date().getTime() - 300 * 1000);
        this.initProgress = this.deviceList.length;
        for (var i = 0; i < this.deviceList.length; i++) {
            this.dataSet['d' + i] = []
        }

        this.setTimeLine(this.timeFormat);
        this.initOptions(i, 300);

        // $('#chartbox').on('mouseenter', function () {
        //     // console.log('hover')
        //     // clearInterval(that.timer)
        // });
        // $('#chartbox').on('mouseleave', function () {
        //     // now = new Date();应该是开始移动的时间
        //     // console.log('out')
        //     // that.move();
        // });
        var that = this;
        this.timer = setInterval(function () {
            console.log(that.timer)
            that.move();
        }, that.gap);

    },
    setTimeLine: function (type) {//设置时间轴
        this.curTime = new Date();
        for (var i = 0; i < 300; i++) {
            var time = utils.formatDisplayTime(new Date(this.curTime.getTime() - ((300 - i) * this.gap)), type);
            this.timeLine.push(time);
        }
    },
    initData: function (idx, count, cb) {
        var that = this;
        $.ajax({
            url: utils.apiDomain + 'deviceRecord/getDeviceInfoList',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                deviceId: that.deviceList[idx],
                count: count,
                fromTime: utils.formatTime(new Date(new Date().getTime() - count * 1000)),
                toTime: utils.formatTime(new Date()),
                page: 1,
                showAlarm: false,
                type: 0
            },
            success: function (data) {
                unlogin(data)

                //mock
                // data = that.mock(300)
                //mock end

                //获取所需要的数据放入图表
                data.data.list.forEach(function (el) {
                    that.dataSet['d' + idx].unshift(el.doserate)
                });
                that.dataSet['markline'] = []
                for (var i = 0; i < count; i++) {
                    that.dataSet['markline'].push(that.markline)
                }
                cb && cb()
            }
        })
    },
    updateData: function (idx, count, cb) {
        var that = this;
        $.ajax({
            url: utils.apiDomain + 'deviceRecord/getDeviceInfoList',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                deviceId: that.deviceList[idx],
                count: count,
                fromTime: utils.formatTime(new Date(this.curTime.getTime() - count * 1000)),
                toTime: utils.formatTime(new Date(this.curTime.getTime())),
                page: 1,
                showAlarm: false,
                type: 0
            },
            success: function (data) {
                unlogin(data)
                //mock
                // data = that.mock(300)
                //mock end

                //获取所需要的数据放入图表
                data.data.list.forEach(function (el) {
                    that.dataSet['d' + idx].push(el.doserate)
                });
                for (var i = 0; i < count; i++) {
                    that.dataSet['markline'].push(that.markline)
                }
                cb && cb()
            }
        })
    },
    initOptions: function () {
        var that = this;
        // 指定图表的配置项和数据
        this.option = {
            title: {
                text: '',
            },
            tooltip: {
                trigger: 'axis'
            },
            color: ['#ff0000', '#00bda0', '#fd8a02', '#fed105', '#41b9e6', '#e64164', '#68dab1', '#0093c7 ', '#647ad7', '#d79764', '#e9da71'],
            legend: {
                textStyle: {
                    color: '#fff'
                },
                inactiveColor: '#aaa',
            },
            xAxis: {
                type: 'category',
                splitLine: {
                    show: true,
                },
                data: this.timeLine,
                axisLine: {
                    lineStyle: {
                        color: '#2FAEF5',
                        width: 3,//这里是为了突出显示加上的
                    }
                }
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, 1],
                splitLine: {
                    show: true,
                    color: 'red'
                },
                axisLine: {
                    lineStyle: {
                        color: '#2FAEF5',
                        width: 3,//这里是为了突出显示加上的
                    }
                }
            },
            series: [

            ]
        };
        this.deviceList.forEach(function (id, idx) {
            that.option.series.push({
                name: '设备ID' + id,
                type: 'line',
                showSymbol: false,
                hoverAnimation: true,
                data: that.dataSet['d' + idx]
            })
            that.initData(idx, 300, function () {
                that.initProgress--;
                if (that.initProgress == 0) {
                    that.option.series.unshift({
                        name: '报警阀值',
                        type: 'line',
                        showSymbol: false,
                        hoverAnimation: true,
                        data: that.dataSet['markline']
                    })
                    myChart.setOption(that.option);
                }
            })
        })



    },
    mock: function (num) {//返回指定数量的模拟数据
        data = {
            "data": {
                "list": [],
                "total": 0
            },
        }
        for (var j = 0; j < num; j++) {
            data.data.list.push(
                {
                    "battery": 0,
                    "cps": 0,
                    "deviceId": 0,
                    "doserate": 1 + Math.random(),
                    "flagAlarm": 0,
                    "id": 0,
                    "nickname": "string",
                    "offline": true,
                    "time": "2018-08-22T15:47:08.711Z"
                },
            )
        }
        return data
    },
    move: function () {
        // console.log('chart move')
        var that = this
        for (var key in this.dataSet) {
            this.dataSet[key].shift()
        }
        this.timeLine.shift()
        this.curTime = new Date(this.curTime.getTime() + 1000)
        var time = utils.formatDisplayTime(this.curTime, this.timeFormat);
        this.timeLine.push(time)

        that.option.xAxis.data = this.timeLine
        that.initProgress = that.deviceList.length;

        this.deviceList.forEach(function (id, idx) {
            that.updateData(idx, 1, function () {
                that.initProgress--;
                if (that.initProgress == 0) {
                    that.option.series[idx + 1].data = that.dataSet['d' + idx];
                    myChart.setOption(that.option);
                }
            })
        })
    },
    clearAll: function () {
        console.log('clearAll')
        clearInterval(this.timer);
    }
};

function getChart(flag) {
    if (flag) {
        myChart = echarts.init($box);
        chartData.init();
    } else {
        chartData.clearAll();
        $('#chartbox').css('zIndex', -1);
    }
}
